import React, { useEffect, useState } from 'react'
import { Root, Root2 } from '../types/menuItem'
import { Route, Routes, useLocation, useNavigate } from 'react-router-dom'
import { Suspense, lazy } from 'react'

import { useAppSelector } from '../store/hooks'

interface RouteConfig {
  path: string
  Component: React.LazyExoticComponent<any>
  exact?: boolean
  children?: RouteConfig[]
}

// 所有动态路由表，需要鉴权筛选
const routeComponents = {
  '/': lazy(() => import('@/pages/Echarts')),
  '/orderList': lazy(() => import('@/pages/order')),
  '/orderUpdate': lazy(() => import('@/pages/orderUpdate')),
  '/orderDetails': lazy(() => import('@/pages/OrderDetails')),
  '/reTurns': lazy(() => import('@/pages/ReTurns/Index')),
  '/userList': lazy(() => import('@/pages/userList')),
  '/roleList': lazy(() => import('@/pages/roleList')),
  '/menuList': lazy(() => import('@/pages/menuList')),
  '/excelList': lazy(() => import('@/pages/ExcelList')),
  '/upload': lazy(() => import('@/pages/Upload')),
  '/roleUpdate': lazy(() => import('@/pages/roleList/setRole')),
  '/commodity/commodityList': lazy(
    () => import('@/pages/commodity/commodityList')
  ), // 商品列表
  '/commodity/addCommodity': lazy(
    () => import('@/pages/commodity/addCommodity')
  ), // 添加商品
  '/commodity/commodityClassification': lazy(
    () => import('@/pages/commodity/commodityClassification')
  ), // 商品分类
  '/commodity/commodityType': lazy(
    () => import('@/pages/commodity/commodityType')
  ), // 商品类型
  '/commodity/brandManagement': lazy(
    () => import('@/pages/commodity/brandManagement')
  ), // 品牌管理
  '/commodity/brandManagementEdit': lazy(
    () => import('@/pages/commodity/brandManagementEdit')
  ) // 品牌管理编辑
}

// 所有静态路由表
const staticRoutes: RouteConfig[] = [
  {
    path: '/login',
    Component: lazy(() => import('@/pages/login'))
  },
  {
    path: '/',
    Component: lazy(() => import('@/pages/Front')),
    children: []
  },
  {
    path: '*',
    Component: lazy(() => import('@/pages/404'))
  },
  {
    path: '/reset',
    Component: lazy(() => import('@/pages/Reset'))
  },
  {
    path: '/resetpwd',
    Component: lazy(() => import('@/pages/ReatPwd'))
  },
  {
    path: '/register',
    Component: lazy(() => import('@/pages/Register'))
  }
]

export default function RouteManager() {
  const location = useLocation()
  const navigate = useNavigate()
  // 获取用户权限
  const Menus = useAppSelector((state) => state.front.Menus)
  // 动态路由
  const [routes, setRoutes] = useState<RouteConfig[]>(staticRoutes)

  // 调用方法对所拥有的权限显示对应的路由
  const convertMenuToRoutes = (menu: Root): RouteConfig[] => {
    const routes: RouteConfig[] = []
    const processMenuItem = (item: Root2) => {
      if (item.children) {
        item.children.forEach(processMenuItem)
      } else {
        if (routeComponents[`/${item.key}`]) {
          routes.push({
            path: `/${item.key}`,
            Component: routeComponents[`/${item.key}`],
            exact: true
          })
        }
      }
    }
    menu.forEach(processMenuItem)
    return routes
  }

  // 获取用户权限
  useEffect(() => {
    if (Menus.length === 0) {
      if (
        location.pathname === '/register' ||
        location.pathname === '/reset' ||
        location.pathname === '/resetpwd'
      ) {
        return
      }
      navigate('/login')
      return
    }
    const dynamicRoutes = convertMenuToRoutes(Menus)
    setRoutes((prevRoutes) => {
      const homeRoute = prevRoutes.find((route) => route.path === '/')
      if (homeRoute) {
        homeRoute.children = dynamicRoutes
      }
      return [...prevRoutes]
    })
  }, [Menus, navigate, location.pathname])

  return (
    <Suspense fallback={<div></div>}>
      <Routes>
        {routes.map((route, index) => {
          if (route.children) {
            return (
              <Route
                key={index}
                path={route.path}
                element={<route.Component />}
              >
                {route.children.map((child, idx) => (
                  <Route
                    key={idx}
                    path={child.path}
                    element={<child.Component />}
                  />
                ))}
              </Route>
            )
          }
          return (
            <Route
              key={index}
              path={route.path}
              element={<route.Component />}
            />
          )
        })}
      </Routes>
    </Suspense>
  )
}
